package com.example.demo.project.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.common.utils.redis.RedisUtil;
import com.example.demo.project.dao.QQUserDao;
import com.example.demo.project.entity.QQUser;
import com.example.demo.project.entity.User;
import com.example.demo.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {
    @Value("${img.upload.path}")
    private String imgUploadPath;
    @Value("${img.see.path}")
    private String imgSeePath;
    @Autowired
    private UserService userService;
    @Autowired
    private QQUserDao qqUserDao;
    //用户登入判断
    @PostMapping("/login")
    public Result login(@RequestBody User user){

        // 获取redis中的验证码
        Object redisCode = RedisUtil.Get(user.getVerKey());
        if(redisCode==null){
            return Result.error(600,"验证码已过期");
        }
        // 判断验证码
        if (user.getVerCode()==null) {
            return Result.error(600,"验证码不能为空");
        }
        if(!redisCode.toString().equals(user.getVerCode().trim().toLowerCase())){
            return Result.error(600,"验证码不正确");
        }
        if(userService.login(user)!=null){
            return Result.success(userService.login(user));
        }
        return Result.error(600,"账号或密码不正确");
    }
    //获取用户信息
    @GetMapping("/getUser")
    public Result getUser(@RequestParam String username){
        return Result.success(userService.getUser(username));
    }
    //获取消息列表
    @GetMapping("/news")
    public Result getNews(@RequestParam String newsId){
        return Result.success(qqUserDao.findOneQQNews(newsId));
    }
    //获取申请列表
    @GetMapping("/noUser")
    public Result getNoUser(@RequestParam String username){
        QQUser qqUserOne = qqUserDao.findOneQQUser(username);
        ArrayList noUserList = qqUserOne.getNoUserList();
        JSONArray array2 = new JSONArray();
        for(int i=0;i<noUserList.size();i++){
            User user = userService.getUser(noUserList.get(i).toString());
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("username",user.getUsername());
            jsonObject.set("name",user.getName());
            jsonObject.set("img",user.getImg());
            array2.add(jsonObject);
        }
        return Result.success(array2);
    }
    @GetMapping("/applyFriend")
    public Result applyFriend(@RequestParam String username1,@RequestParam String username2) {
                //申请好友
        boolean flag=qqUserDao.applyFriend(username1,username2,true);
        return Result.success(flag);
    }
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "1") Long pageNum,
                           @RequestParam(defaultValue = "4") Long pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String username
    ){
        IPage<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        if(!"".equals(username)){
            queryWrapper.like("username",username);
        }
        return Result.success(userService.page(page,queryWrapper));
    }
    @GetMapping("/changePer")
    public void changePer(@RequestParam String  username){
        User user=userService.getUser(username);
        if(user.getPer()==0){
            user.setPer(1);
        }else {
            user.setPer(0);
        }
        userService.saveOrUpdate(user);
    }
    //新增和修改
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        return Result.success(userService.saveOrUpdate(user));
    }
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 获取源文件的名称
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        // 定义文件的唯一标识（前缀）
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid+ StrUtil.DOT+type;
        File uploadFile = new File(imgUploadPath+fileUuid);
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        file.transferTo(uploadFile);
        String url;
        url = imgSeePath+fileUuid;
//        url = "http://localhost:8080/imgs/"+fileUuid;
        return Result.success(url);
    }
}
